﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FourWayClimbingDemo.Chess.Rule
{
    /// <summary>
    /// 移动棋子规则
    /// </summary>
    public class MoveChessPieceRule : IRule
    {
        private ChessBoard _chessBoard;
        private Player _player;
        private ChessPiece _chessPiece;
        private Dir _dir;

        public MoveChessPieceRule(ChessBoard chessBoard, Player player, ChessPiece chessPiece, Dir dir) {
            this._chessBoard = chessBoard;
            this._player = player;
            this._chessPiece = chessPiece;
            this._dir = dir;
        }

        public bool Execute()
        {
            // var pos = _chessPiece.GetPosition();

            var pos = _chessBoard.GetChessPieceAround(_chessPiece,_dir);
            //检查位置是否合法
            if (pos == null) return false;
            int row = pos.Value.row;
            int col = pos.Value.col;
            //检查此处是否有棋子
            if (_chessBoard.IsEmpty(row, col)) {
                //移动棋子
                _chessPiece.Move(row,col);
                return true;
            }

            //检查是否是自己的棋子
            if (_player.GetChessPiece(row, col) != null) return false;

            //是对方的棋子，检查是否能吃掉
            //检查跳过去的位置
            var pos1 = _chessBoard.GetChessPieceAround(row,col,_dir);

            //检查位置是否合法
            if (pos1 == null) return false;
            int row1 = pos1.Value.row;
            int col1 = pos1.Value.col;
            //检查此处是否有棋子
            if (_chessBoard.IsEmpty(row1, col1)) {
                //移动并吃掉对方棋子
                _chessPiece.Move(row1,col1);
                _chessBoard.RemoveChessPiece(row,col);
                return true;
            }
            return false;
        }
    }
}
